package org.chen.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.chen.config.BatchStatsManager;
import org.chen.dto.CommentUrlDTO;
import org.chen.model.CommentBatch;
import org.chen.service.impl.BatchListServiceImpl;
import org.chen.service.impl.CommentBatchServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/list")
@Slf4j
public class ListCommentController {
    @Autowired
    private BatchListServiceImpl batchListService;

    @Autowired
    private BatchStatsManager batchStatsManager;

    @GetMapping("/batch/list")
    public ResponseEntity<IPage<CommentBatch>> getBatchList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        IPage<CommentBatch> batchPage = batchListService.getBatchList(current, pageSize);
        return ResponseEntity.ok(batchPage);
    }

    @DeleteMapping("/batch/{batchNo}")
    public ResponseEntity<Void> deleteBatch(@PathVariable String batchNo) {
        batchListService.deleteBatchWithTasks(batchNo);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/batch/delete")
    public ResponseEntity<Void> deleteBatches(@RequestBody List<String> batchNos) {
        batchListService.deleteBatchesWithTasks(batchNos);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/batch/export-urls")
    public ResponseEntity<List<CommentUrlDTO>> exportCommentUrls(@RequestBody List<String> batchNos) {
        log.info("Received batchNos: {}", batchNos);
        List<CommentUrlDTO> urls = batchListService.getSuccessCommentUrls(batchNos);
        return ResponseEntity.ok(urls);
    }

    /**
     * 批量同步多个批次状态
     */
    @PostMapping("/sync/batch")
    public ResponseEntity<Map<String, String>> syncBatchStatuses(@RequestBody List<String> batchNos) {
        Map<String, String> results = new HashMap<>();

        for (String batchNo : batchNos) {
            try {
                batchStatsManager.syncBatchStatus(batchNo);
                results.put(batchNo, "成功");
            } catch (Exception e) {
                results.put(batchNo, "失败: " + e.getMessage());
            }
        }

        return ResponseEntity.ok(results);
    }
}
